<template>
  <v-container class="tenantManagement-container" fluid>
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-title>
            <!-- 主要操作按钮 -->
            <v-btn v-if="perms('generator_template_insert')" color="primary" prepend-icon="mdi-plus" class="mr-2"
              @click="handleInsert">
              添加
            </v-btn>
            <v-btn v-if="perms('generator_template_copy')" :disabled="selectRows.length !== 1" color="warning"
              prepend-icon="mdi-content-copy" class="mr-2" @click="handleCopy">
              复制
            </v-btn>
            <v-btn v-if="perms('generator_template_delete') && selectRows.length > 0" color="error"
              prepend-icon="mdi-delete" class="mr-2" @click="handleBatchDelete">
              批量删除
            </v-btn>
          </v-card-title>

          <v-card-text>
            <!-- 查询表单 -->
            <v-form @submit.prevent="queryData">
              <v-row>
                <v-col cols="4">
                  <v-text-field v-model="queryForm.tempName_LIKE" label="请输入模板名称" clearable density="compact"
                    variant="outlined" />
                </v-col>
                <v-col cols="4">
                  <v-select v-model="queryForm.tableType_EQ" :items="dict.table_type" item-title="dictName"
                    item-value="dictValue" label="请选择表类型" clearable density="compact" variant="outlined" />
                </v-col>
                <v-col cols="2">
                  <v-btn color="primary" prepend-icon="mdi-magnify" @click="queryData">
                    查询
                  </v-btn>
                </v-col>
              </v-row>
            </v-form>

            <!-- 数据表格 -->
            <v-data-table :loading="listLoading" :items="list" :headers="headers" show-select v-model="selectRows"
              item-value="id" class="mt-4" :page="queryForm.pageNo" :items-per-page="queryForm.pageSize"
              :server-items-length="total" @update:page="handleCurrentChange" @update:items-per-page="handleSizeChange">
              <template v-slot:item.index="{ index }">
                {{ (queryForm.pageNo - 1) * queryForm.pageSize + index + 1 }}
              </template>

              <template v-slot:item.tableType="{ item }">
                <span>{{ getDictNameByValue('table_type', item.tableType) }}</span>
              </template>

              <template v-slot:item.actions="{ item }">
                <v-btn v-if="perms('generator_template_update')" variant="text" size="small"
                  @click="handleUpdate(item)">
                  编辑
                </v-btn>
                <v-divider vertical class="mx-2"></v-divider>
                <v-btn v-if="perms('generator_template_delete')" variant="text" size="small" color="error"
                  @click="handleDelete(item)">
                  删除
                </v-btn>
              </template>
            </v-data-table>

            <!-- 分页 -->
            <!-- <v-pagination v-model="queryForm.pageNo" :length="Math.ceil(total / queryForm.pageSize)" :total-visible="7"
              @update:model-value="handleCurrentChange" class="mt-4" /> -->
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- 编辑弹窗 -->
    <Edit ref="editRef" @fetchData="fetchData" />

    <!-- 复制模板名称输入弹窗 -->
    <v-dialog v-model="copyDialog" max-width="400px">
      <v-card>
        <v-card-title>复制模板</v-card-title>
        <v-card-text>
          <v-text-field v-model="copyForm.tempName" label="请输入新模板名称" :rules="copyNameRules" variant="outlined"
            density="compact" />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn color="grey-darken-1" variant="text" @click="copyDialog = false">
            取消
          </v-btn>
          <v-btn color="primary" variant="text" @click="confirmCopy">
            确定
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import Edit from './components/GenTemplateManagementEdit.vue';
import { getList, doDelete, doCopy } from '@/api/generator/template/GenTemplateManagement';
import { isNull } from '@/utils/validate';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const list = ref<any[]>([]);
const listLoading = ref(true);
const total = ref(0);
const selectRows = ref<string[]>([]);
const copyDialog = ref(false);

const queryForm = reactive({
  pageNo: 1,
  pageSize: 10,
  tempName_LIKE: '',
  tableType_EQ: '',
});

const dict = reactive({
  table_type: [] as any[],
} as Record<string, any[]>);

const copyForm = reactive({
  tempName: '',
  sourceId: '',
});

// 表头配置
const headers = [
  { title: '序号', key: 'index', width: 95, sortable: false },
  { title: '模板名称', key: 'tempName' },
  { title: '表类型', key: 'tableType', width: 150 },
  { title: '备注', key: 'remark' },
  { title: '操作', key: 'actions', sortable: false, width: 150 },
];

// 复制名称验证规则
const copyNameRules = [
  (v: string) => !!v || '模板名称不能为空',
  (v: string) => /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/.test(v) || '只能包含汉字、字母、数字和下划线',
];

// 权限判断
function perms(key: string) {
  // TODO: 实现权限判断逻辑
  return true;
}

// 字典名称转换
function getDictNameByValue(type: string, value: string) {
  const item = dict[type]?.find((d: any) => d.dictValue === value);
  return item ? item.dictName : value;
}

// 新增模板
function handleInsert() {
  (editRef.value as any)?.showEdit();
}

// 编辑模板
function handleUpdate(row: any) {
  if (row.id) {
    (editRef.value as any)?.showEdit(row);
  }
}

// 复制模板
function handleCopy() {
  if (selectRows.value.length !== 1) {
    showError('请选择一个模板进行复制');
    return;
  }

  const selectedItem = list.value.find(item => item.id === selectRows.value[0]);
  if (selectedItem) {
    copyForm.sourceId = selectedItem.id;
    copyForm.tempName = `${selectedItem.tempName}_复制`;
    copyDialog.value = true;
  }
}

// 确认复制
async function confirmCopy() {
  if (!copyForm.tempName.trim()) {
    showError('请输入模板名称');
    return;
  }

  if (!/^[\u4e00-\u9fa5a-zA-Z0-9_]+$/.test(copyForm.tempName)) {
    showError('模板名称只能包含汉字、字母、数字和下划线');
    return;
  }

  try {
    const { data } = await doCopy({
      id: copyForm.sourceId,
      tempName: copyForm.tempName
    });
    showSuccess(data?.msg || '复制成功');
    copyDialog.value = false;
    fetchData();
  } catch (error) {
    console.error('复制失败:', error);
  }
}

// 删除模板
async function handleDelete(row: any) {
  if (!row.id) return;

  // TODO: 实现确认对话框
  if (confirm('确定要删除这个模板吗？')) {
    try {
      const { data } = await doDelete({ id: row.id });
      showSuccess(data?.msg || '删除成功');
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
    }
  }
}

// 批量删除
async function handleBatchDelete() {
  if (selectRows.value.length === 0) {
    showError('请选择要删除的模板');
    return;
  }

  if (confirm(`确定要删除选中的 ${selectRows.value.length} 个模板吗？`)) {
    try {
      // 批量删除逻辑
      for (const id of selectRows.value) {
        await doDelete({ id });
      }
      showSuccess('批量删除成功');
      selectRows.value = [];
      fetchData();
    } catch (error) {
      console.error('批量删除失败:', error);
    }
  }
}

// 分页大小变化
function handleSizeChange(val: number) {
  queryForm.pageSize = val;
  queryForm.pageNo = 1;
  fetchData();
}

// 页码变化
function handleCurrentChange(val: number) {
  queryForm.pageNo = val;
  fetchData();
}

// 查询数据
function queryData() {
  queryForm.pageNo = 1;
  fetchData();
}

// 获取数据
async function fetchData() {
  listLoading.value = true;
  try {
    const { data } = await getList(queryForm);
    if (!isNull(data)) {
      list.value = data?.rows || data.rows || [];
      total.value = data?.total || data.total || 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    setTimeout(() => {
      listLoading.value = false;
    }, 300);
  }
}

// 初始化字典数据
function initDict() {
  try {
    dict.table_type = getDictListSync('table_type') || [];
  } catch (error) {
    console.error('获取字典数据失败:', error);
    dict.table_type = [];
  }
}

// 组件引用
const editRef = ref();

// 生命周期
onMounted(() => {
  initDict();
  fetchData();
});
</script>

<style lang="scss" scoped>
.tenantManagement-container {
  padding: 24px;
}

.v-data-table {
  border: 1px solid rgba(0, 0, 0, 0.12);
  border-radius: 4px;
}

.v-divider {
  margin: 0 8px;
}
</style>
